package com.szsh.aiot.hsm.config;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * 自定义OkHttp
 */
@Configuration
public class OkHttpConfig {

    /** 连接超时时间 单位：毫秒*/
    @Value("${okhttp3.connect-timeout}")
    private int connectTimeout;
    /** 写超时时间 单位：毫秒 */
    @Value("${okhttp3.write-timeout}")
    private int writeTimeout;
    /** 读取超时时间 单位：毫秒 */
    @Value("${okhttp3.read-timeout}")
    private int readTimeout;
    /** 最大请求数 */
    @Value("${okhttp3.dispatcher.max-requests}")
    private int maxRequests;
    /** 同一个 host 最大请求数 */
    @Value("${okhttp3.dispatcher.max-requests-per-host}")
    private int maxRequestsPerHost;
    /** 最大空闲连接池数量 */
    @Value("${okhttp3.connection.max-idle-connections}")
    private int maxIdleConnections;
    /** 连接的存活时间 单位：分钟 */
    @Value("${okhttp3.connection.keep-alive-duration}")
    private long keepAliveDuration;

    @Bean
    public OkHttpClient okHttpClient(SSLSocketFactory sslSocketFactory, X509TrustManager x509TrustManager) {
        Dispatcher dispatcher = new Dispatcher();
        // 最大请求数
        dispatcher.setMaxRequests(maxRequests);
        // 同一个 host 最大请求数
        dispatcher.setMaxRequestsPerHost(maxRequestsPerHost);

        ConnectionPool connectionPool = new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.MINUTES);

        return new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .sslSocketFactory(sslSocketFactory, x509TrustManager)
                .hostnameVerifier((s, sslSession) -> true)
                .build();
    }

    @Bean
    public SSLSocketFactory sslSocketFactory(X509TrustManager x509TrustManager) throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
        return sslContext.getSocketFactory();
    }

    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
}
